<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2017/12/15
 * Time: 10:58
 */

namespace Biz\service;


use Biz\model\tiles\TilesRecords;
use Biz\model\tiles\TopupOptions;
use Biz\model\tiles\UserTilesBalance;
use Biz\module\Packages\Pay\IAP;
use Biz\module\Packages\Pay\Tiles as pTiles;
use Biz\service\course\Course;
use Doraemon\service\User;
use Doraemon\tools\IdParse;
use Doraemon\tools\Log;
/**
 * @deprecated
 */
class Tiles
{
    const TOPUP_TIPS = "1、好好住瓦片可用于直接购买好好住 App 内虚拟内容（不含实体商品、线下课程等）
2、iOS 系统的瓦片只能在其系统使用，不能用于其他平台
3、好好住瓦片为虚拟币，充值后的瓦片不会过期，但无法提现或转赠他人";
    const TOPUP_RECORD_INFO = '充值成功';
    const COURSE_RECORD_INFO = '购买课程-';
    const TILES_UNIT = '瓦片';

    public static function topupBllance($uid, $iapData)
    {
        $result = ['success' => 0];
        Log::info('苹果iap支付返回信息', [
            'ipaData' => $iapData
        ]);
        if ($iapData && $iapData['receipt']['in_app']) {
            $result['success'] = 1;
            foreach ($iapData['receipt']['in_app'] as $transaction) {
                $record = TilesRecords::getRecordByTransactionId($transaction['transaction_id']);
                if ($record) {
                    Log::warning('苹果iap支付transaction_id记录已存在', [
                        'record'     => $record,
                        'transation' => $transaction
                    ]);
                    continue;
                }
                $option = TopupOptions::getOptionByAppleProductId($transaction['product_id']);
                if (empty($option)) {
                    Log::warning('苹果iap支付transaction_id记录已存在', [
                        'record'     => $record,
                        'transation' => $transaction
                    ]);
                    continue;
                }
                $topUpOrderNo = self::genTopupOrderNo($option['option_id'], $uid);
                IAP::createOrder([
                    'order_no'   => $topUpOrderNo,
                    'pay_amount' => $option['price'],
                    'pay_ver'    => IAP::_PAY_VER_DEFAULE
                ], [
                    'order_type'    => IAP::_PAY_ORDER_TYPE_TILES,
                    'pay_no'        => $transaction['transaction_id'],
                    'pay_time'      => date('Y-m-d H:i:s', strtotime($transaction['purchase_date'])),
                    'callback_info' => $transaction
                ]);
                $addRecordResult = TilesRecords::addTopupRecord($uid, TilesRecords::RECORD_TYPE_TOPUP, $option['tiles_num'], $topUpOrderNo, $transaction['transaction_id'], self::TOPUP_RECORD_INFO, date('Y-m-d H:i:s', strtotime($transaction['purchase_date'])));
                if ($addRecordResult) {
                    UserTilesBalance::addUserBalance($uid, $option['tiles_num']);
                } else {
                    Log::warning('交易记录添加失败', [
                        'record'     => $record,
                        'transation' => $transaction
                    ]);
                    $result['success'] = 0;
                    continue;
                }
                $result['order_no'] = $topUpOrderNo;
                $result['pay_amount'] = $option['price'];
            }
        }
        return $result;
    }

    public static function consumeTiles($uid, $orderInfo)
    {
        $userBalance = self::getUserBalance($uid);
        if ($userBalance < $orderInfo['pay_amount']) {
            throw new \Exception('余额不足');
        }
        //扣减余额
        self::consumeUserBalance($uid, $orderInfo);
        //创建支付单信息
        pTiles::createOrder([
            'order_no'   => $orderInfo['order_no'],
            'pay_amount' => $orderInfo['pay_amount'],
            'pay_ver'    => pTiles::_PAY_VER_DEFAULE
        ], [
            'order_type'    => pTiles::_PAY_ORDER_TYPE_COURSE,
            'pay_time'      => date('Y-m-d H:i:s'),
            'pay_no'        => $orderInfo['order_no'],
            'callback_info' => ''
        ]);
        return true;
    }

    private static function genTopupOrderNo($optionId, $uid)
    {
        $microTime = bcmul(microtime(true), 10000);
        $microTime = sprintf('%s%s', date('His'), substr($microTime, -4, 3));
        $microTime = strtoupper(base_convert($microTime, 10, 32));
        $time = date('ymd');
        $parseId = strtoupper(base_convert($optionId, 10, 32));
        $hashUid = IdParse::hashUid($uid);
        $order = [
            $time,
            $microTime,
            $parseId,
            $hashUid
        ];
        $orderNo = implode('-', $order);
        $info = TilesRecords::getRecordByOrderNo(['order_no' => $orderNo]);
        if (!empty($info)) {
            self::genTopupOrderNo($optionId, $uid);
        }
        return $orderNo;
    }

    public static function getWalletHistory($uid, $page = 1)
    {
        $userBalance = self::getUserBalance($uid);
        $history = TilesRecords::getHistory($uid, $page);
        $formatHistoryList = [];
        if ($history['history_list']) {
            foreach ($history['history_list'] as $record) {
                $formatHistoryList[] = [
                    "record_type" => $record['record_type'],
                    "amount"      => $record['amount'],
                    "record_info" => $record['record_info'],
                    "record_time" => $record['record_time'],
                ];
            }
        }
        return [
            'balance'      => $userBalance,
            'history_list' => $formatHistoryList,
            'is_over'      => $history['is_over']
        ];

    }

    public static function getTopupOptions($uid, $courseId = null)
    {
        $options = TopupOptions::getTopupOptions();
        $balance = self::getUserBalance($uid);
        $difference = 0;
        if ($courseId) {
            $courseInfo = Course::getCourseInfo($courseId);
            $difference = $balance >= $courseInfo['price'] ? 0 : bcsub($courseInfo['price'], $balance, 2);
        }
        $formatData = [
            'balance'    => $balance,
            'difference' => $difference,
            'pay_tips'   => self::TOPUP_TIPS
        ];
        $bestOption = false;
        foreach ($options as $option) {
            $formatOption = [
                'app_gid' => $option['product_id'],
                'price'   => "￥" . $option['price'],
                'tiles'   => floatval($option['tiles_num']) . self::TILES_UNIT,
            ];
            if (!$bestOption && $option['tiles_num'] >= $difference) {
                $formatOption['is_selected'] = 1;
                $bestOption = true;
            }
            $formatData['options_list'][] = $formatOption;
        }
        return $formatData;
    }

    public static function getUserBalance($uid)
    {
        return UserTilesBalance::getUserBalance($uid);
    }

    public static function consumeUserBalance($uid, $orderInfo)
    {
        $result = UserTilesBalance::consumeUserBalance($uid, $orderInfo['pay_amount']);
        if ($result) {
            TilesRecords::addTopupRecord($uid, TilesRecords::RECORD_TYPE_COURCE, -$orderInfo['pay_amount'], $orderInfo['order_no'], $orderInfo['order_no'], self::COURSE_RECORD_INFO . $orderInfo['title'], date('Y-m-d H:i:s'));
        } else {
            throw new \Exception('扣减瓦片失败');
        }
    }

    public static function admGetHistory($where)
    {
        $history = TilesRecords::admGetHistory($where);
        $uids = array_column($history['list'], 'uid');
        $userInfos = User::getBatchBasicUserInfo($uids);
        $userInfos = array_column($userInfos, null, 'uid');
        foreach ($history['list'] as &$item) {
            $item['nick'] = isset($userInfos[$item['uid']]) ? $userInfos[$item['uid']]['nick'] : '';
        }
        return $history;
    }
}